// 这里和http后台请求token不一样， 要另起一个
import axios from "axios";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { ChatQuery, FileForm, DeleteFileQuery, ChatTestQuery } from "./types";
import { Function } from "estree";
const BASE_API = import.meta.env.VITE_APP_BASE_API

/**
//     "messages": [{
//         "role": "user",
//         "content": "介绍一下Llama社区"
//     }],
**/
export function chatApi(message: ChatQuery, onmessage: Function): any {
  const messages =  [{
      role: "user",
      content: message.question,
    }];
  const ctrl = new AbortController();
  return fetchEventSource(`${BASE_API}/buss/ai/completion`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(messages),
    signal: ctrl.signal,
    onmessage: (evt) => {
      const data = JSON.parse(evt.data);
      if (data instanceof Array) {
        data.forEach(it => {
          const itData = it.data;
          if (itData != 'data:' && itData != '\n\n') {
            onmessage(itData)
          }
        })
      } else {
        onmessage(evt)
      }
    }
  });
}

// 与模型对话
export function chat(data?: ChatQuery): any {
  return axios({
    url: "ai/chat",
    method: "post",
    data: data,
  });
}

// 与知识库对话
export function chatKnowledge(data?: ChatQuery): any {
  return axios({
    url: "ai/local_doc_qa/local_doc_chat",
    method: "post",
    data: data,
  });
}

/**
 * 上传文件到知识库
 *
 * @param file
 */
export function uploadFileApi(file: File, form: FileForm) {
  const formData = new FormData();
  formData.append("file", file);
  // 知识库编号
  formData.append("knowledge_base_id", form.knowledgeId);

  return axios({
    url: "ai/local_doc_qa/upload_file",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

/**
 * 删除文件
 *
 * @param filePath 文件完整路径
 */
export function deleteFileApi(params?: DeleteFileQuery) {
  return axios({
    url: `ai/local_doc_qa/delete_file`,
    method: "delete",
    params: params,
  });
}
